/**
 * 系统后台单表配置服务JS-SingleTableService.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";
var editcacheparmetercode = 0;//(0，初始化1,添加条件字段缓存配置；2，修改)
$(function () {
    //参数
    $("#hid_servertype").val(GetQueryString("servertype"));//服务类型 添加使用
    $("#hid_operate").val(GetQueryString("operate")); //操作类型
    $("#hid_serviceId").val(GetQueryString("servercode"));//服务ID  修改使用
    $("#hid_projectid").val(GetQueryString("projectid"));//工程ID 添加修改预留
    $("#dtConfigId").select2();

    //默认生成服务ID
    $("#guid").val(GetQueryString("projectid") + "_" + "singleTable_" + randomWord(false, 4, 4));

    function randomWord(randomFlag, min, max) {
        var str = "",
            range = min,
            arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        // 随机产生
        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        for (var i = 0; i < range; i++) {
            pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    }

    //绑定数据源标识
    $.ajax({
        type: 'POST',
        // url: postPath + '/system/singleTable/getAllDataSource',
        url: postPath + '/system/sysProject/getProjectToDataSource?pcode=' + GetQueryString("projectid"),
        async: false,
        success: function (res) {
            $("#dbKey").append('');
            var strtxt = "<option value=''>请选择</option>";
            if (res.success) {
                $.each(res.data, function (i, e) {
                    strtxt += "<option value='" + e.dbKey + "'>" + e.dbMark + "(" + e.dbKey + ")" + "</option>";
                });
            }
            $("#dbKey").html(strtxt);
        },
        error: function () {
            // bootbox.alert("获取数据源失败!");
            showMsg("获取数据源失败!", "error");
        }
    });

    $("#dbKey").change(function () {
        bindTableList($("#dbKey").val());
    });

    //判断服务修改还是添加
    if ($("#hid_operate").val() == "edit") {
        $.ajax({
            type: 'POST',
            url: postPath + '/system/singleTable/selectDataByGuid',
            async: false,
            data: {guid: $("#hid_serviceId").val()},
            success: function (res) {
                var responseMode = res.responseMode == null || res.responseMode == ''? 0 : res.responseMode
                bindTableList(res.dbKey);
                $("#guid").val(res.guid);
                $("#dbKey").val(res.dbKey);
                $("#dtConfigId").val(res.dtConfigId).trigger("change");
                $("#servicename").val(res.servicename);
                $("#remark").val(res.remark);
                $("#EditContent").modal('show');
                $("input:radio[name='radioSysCatch'][value=" + res.syscatch + "]").attr("checked", true);
                if (res.syscatch == "1") {
                    $("#catchtime").removeAttr("readonly");
                }
                $("input:radio[name='radioPagintion'][value=" + res.ispagination + "]").attr("checked", true);
                $("input:radio[name='radioResponseMode'][value=" + responseMode + "]").attr("checked", true);
                $("#catchtime").val(res.catchtime);
                $("#guid").attr("readonly", "readonly");
                $("#dbKey").attr("readonly", "readonly");
                $("#dtConfigId").attr("readonly", "readonly");
                $('#time_delay').val(res.timeDelay);
            }
        });
    }

    //绑定表标识数据
    function bindTableList(dbkey) {
        $("#dtConfigId").select2("val", "");
        $("#dtConfigId").html("");
        $.ajax({
            type: 'POST',
            url: postPath + '/system/singleTable/tableByKey',
            data: {dbkey: dbkey},
            async: false,
            success: function (data) {
                $.each(data, function (i, e) {
                    // $("#dtConfigId").append("<option value=" + e.dtConfigId + ">" + e.dtNameCn + "</option>");
                    $("#dtConfigId").append("<option value=" + e.dtConfigId + ">" + e.dtName + "</option>");
                });
            }
        });
    }

    //保存信息
    $("#btn_save").click(function () {
        var validateResult = validateData();
        var editUrl = "";
        if ($("#hid_serviceId").val() == "") {
            editUrl = postPath + '/system/singleTable/addSingleTable';
        } else {
            editUrl = postPath + '/system/singleTable/updateSingleTable';
        }
        if (validateResult) {
            var timeDelay = $.trim($('#time_delay').val());
            // console.log("timeDelay:"+timeDelay)

            var pp = {
                guid: $("#guid").val(),
                dbKey: $("#dbKey").val(),
                dtConfigId: $("#dtConfigId").val(),
                servicename: $("#servicename").val(),
                remark: $("#remark").val(),
                // sysCatch: $('input:radio[name="radioSysCatch"]:checked').val(),
                sysCatch: 0,
                isPagination: $('input:radio[name="radioPagintion"]:checked').val(),
                responseMode: $('input:radio[name="radioResponseMode"]:checked').val(),
                catchtime: $('#catchtime').val(),
                pcode: $("#hid_projectid").val(),
                servicetype: $("#hid_servertype").val(),
                timeDelay: 0
                // timeDelay: isNaN(timeDelay) ? 0 : timeDelay
            };

            $.ajax({
                type: 'POST',
                url: editUrl,
                async: false,
                data: JSON.stringify(pp),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                    if (res > 0) {
                        // bootbox.alert("保存成功!");
                        showMsg("保存成功!", "success");
                        $("#hid_serviceId").val($("#guid").val());
                    } else {
                        showMsg("保存失败,请刷新后重试!", "error");
                        // bootbox.alert("保存失败,请刷新后重试!");
                    }
                }
            });
        }
    });

    //返回列表
    $("#btn_back").click(function () {
        var serverType = $("#hid_servertype").val();
        var projectId = $("#hid_projectid").val();
        var seachTxt = (GetQueryStringSeachTxt("seachTxt"));
        window.location.href = postPath + "/prjService/index?order=asc&pageNo=1&pageSize=10&seachTxt=" + seachTxt + "&pcode=" + projectId + '&servertype=' + serverType;
        //retrunIndex();
    });

    //验证信息
    function validateData() {
        if ($("#dbKey").val() == "") {
            $("#errorMessage").html("数据库标识不能为空!");
            return false;
        } else {
            $("#errorMessage").html("");
        }
        if ($("#guid").val() == "") {
            $("#errorMessage").html("服务ID不能为空!");
            return false;
        } else {
            if ($("#hid_serviceId").val() == "") {
                var result = false;
                $.ajax({
                    type: "post",
                    url: postPath + '/system/singleTable/isExistByguid',
                    data: {guid: $("#guid").val()},
                    async: false,
                    success: function (res) {
                        result = res;
                    }
                })
                if (result == true) {
                    $("#errorMessage").html("服务ID已存在!");
                    return false;
                } else {
                    $("#errorMessage").html("");
                }
            } else {
                $("#errorMessage").html("");
            }
        }
        if ($("#servicename").val() == "") {
            $("#errorMessage").html("服务名称不能为空!");
            return false;
        } else {
            $("#errorMessage").html("");
        }
        if ($('input:radio[name="radioSysCatch"]:checked').val() == 1) {
            if ($("#catchtime").val() == "") {
                $("#errorMessage").html("缓存时间不能为空!");
                return false;
            } else {
                var cachetime = $("#catchtime").val();
                var re = /^[1-9]+[0-9]*]*$/; //判断字符串是否为数字
                if (!re.test($("#catchtime").val())) {
                    $("#errorMessage").html("缓存时间为正整数!");
                    return false;
                } else if (cachetime > 100) {
                    $("#errorMessage").html("缓存时间应小于100分钟!");
                    return false;
                }
            }
        } else {
            $("#errorMessage").html();
        }

        return true;

    }

    function getgo() {
        $('#myTab a[href="#tab_1_1_1"]').tab('show');
    };

    //是否缓存点击事件
    $("#sysCatch1").click(function () {
        $("#catchtime").attr("readonly", "readonly");
        $("#catchtime").val("0");
    });
    $("#sysCatch2").click(function () {
        $("#catchtime").removeAttr("readonly");
    });

    /*****************Begin 查询字段配置**********************/
    //查询字段配置选项卡初始化
    $("#a_tab_d").click(function () {
        if ($("#hid_serviceId").val() == "") {
            // bootbox.alert("请先设置单表服务信息!");
            showMsg("请先设置单表服务信息!", "warning");
            setTimeout(getgo, 200);
            return;
        }
        createQueryField();
    });

    //显示查询字段列表
    function createQueryField() {
        var frameSrc = postPath + "/queryConditionConfig/index?serviceId=" + $("#hid_serviceId").val() + "&serviceType=1&grade=";
        $("#queryIframe").attr("src", frameSrc);
    }


    /*****************End 查询字段配置************************/

    /*****************Begin 服务显示字段配置************************/
    //查询字段配置选项卡初始化
    $("#a_tab_c").click(function () {
        if ($("#hid_serviceId").val() == "") {
            // bootbox.alert("请先设置单表服务信息!");
            showMsg("请先设置单表服务信息!", "warning");
            setTimeout(getgo, 200);
            return;
        }
        createShowFieldList();
    });

    //新增显示字段操作
    $("#btn_showAdd").click(function () {
        var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_serviceId").val() + "&serviceType=1&masterDetailId=&operateMethod=add";
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    });

    // here is add update method
    // pass select dataList , first get dataList , then JSON.stringify
    // set parameter into url
    // popup fieldModul
    $("#btn_showUpdate").click(function(){
        var rowList = $("#tb_showfieldList").bootstrapTable("getSelections");
        var jsonDataList = encode_utf8(JSON.stringify(rowList));
        var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_serviceId").val() + "&serviceType=1&masterDetailId=" + "&operateMethod=update&jsonDataList=" + jsonDataList;
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    });


    //新增显示字段Modul关闭监听事件
    $("#FieldModul").on('hidden.bs.modal', function (e) {
        $("#tb_showfieldList").bootstrapTable('refresh');
    });

    //绑定显示字段列表
    function createShowFieldList() {
        //加载数据
        $("#tb_showfieldList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/showfield/getShowFieldList',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            queryParams: {serviceId: $("#hid_serviceId").val(), serviceType: "1"},
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '服务ID',
                field: 'serviceid',
                align: 'center',
                valign: 'middle',
                visible: false,
            }, {
                title: '字段名称',
                field: 'fieldname',
                align: 'center',
                valign: 'middle'
            },{
                title: '自定义字段名称',
                field: 'customAlias',
                align: 'center',
                valign: 'middle'
            },{
                title: '字段标题名称',
                field: 'fieldnameCn',
                align: 'center',
                valign: 'middle'
            }, {
                title: '自定义字段标题名称',
                field: 'customFieldNameAlias',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段类型',
                field: 'fieldtype',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段显示顺序',
                field: 'showorder',
                align: 'center',
                width: '100px',
                valign: 'middle'
            }],
           // onCheck: editShowField,
           // onUncheck: saveShowField
        });
    }

    //修改显示字段信息
    function editShowField(row) {
        $("#tb_showfieldList").find("tr").each(function () {
            var trguid = $(this).attr("data-uniqueid");
            if (trguid == row.guid) {
                var nRow = $(this);
                var jqTds = $('>td', nRow);
                console.log("luowen")
                console.log(jqTds)
                console.log("row is ")
                console.log(row);
                jqTds[6].innerHTML = '<input style="width:60px !important;" id="touchspin_1" type="text" value="' + (row.showorder == null ? "0" : row.showorder) + '">';
                jqTds[2].innerHTML = '<input style="width:160px" id="customAliasId" type="text" value="' + row.customAlias +  '">';
                jqTds[4].innerHTML = '<input style="width:160px" id="customFieldNameAliasId" type="text" value="' + row.customFieldNameAlias +  '">';

            }
        });
        $("#touchspin_1").TouchSpin({
            verticalbuttons: true
        });
    }

    //保存修改显示字段信息
    function saveShowField(row) {
        $("#tb_showfieldList").find("tr").each(function () {
            var trguid = $(this).attr("data-uniqueid");
            if (trguid == row.guid) {
                var nRow = $(this);
                var jqTds = $('>td', nRow);
                var customAlias = $('#customAliasId').val()
                var customFieldNameAlias = $('#customFieldNameAliasId').val()
                var showOrder = $('#touchspin_1').val();
                var temp = {
                    guid: row.guid,
                    serviceid: $("#hid_serviceId").val(),
                    showorder: showOrder,
                    masterdetailid: '',
                    servicetype: 1,
                    customAlias: customAlias,
                    customFieldNameAlias: customFieldNameAlias

                };
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/showfield/updateShowField',
                    async: false,
                    data: JSON.stringify(temp),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data) {
                        $("#tb_showfieldList").bootstrapTable('refresh');
                    }
                });
            }
        });
    }

    //删除服务显示字段
    $("#btn_showDel").click(function () {
        var row = $('#tb_showfieldList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            //showMsg("请选择一行!", "warning");
            return;
        }

        var message = ""
        $.each(row, function(i, e){
            message += e.fieldname + " " + e.fieldnameCn + "<br/>"
        })

        var deleteFunction = function (result) {
            if (result == false)
                return;
            var keys = "";
            $.each(row, function (i, e) {
                keys += e.guid + ",";
            });
            keys = keys.substring(0, keys.length - 1);
            $.ajax({
                url: postPath + '/system/showfield/deleteShowField',
                type: 'POST',
                data: {guids: keys},
                success: function (res) {
                    if (res > 0) {
                        // bootbox.alert("删除成功!");
                        showMsg("删除成功!", "success");
                        $('#tb_showfieldList').bootstrapTable('refresh');
                    } else {
                        // bootbox.alert("删除失败!");
                        showMsg("删除失败!", "error");
                    }
                },
                error: function () {
                    // bootbox.alert("删除失败!");
                    showMsg("删除失败!", "error");
                }
            });
        };

        // here is add message
        confirmDelete( message, deleteFunction);
    });

    /*****************End 服务显示字段配置************************/

    /*****************Start 服务缓存配置************************/
    $("#a_tab_e").click(function () {
        if ($("#hid_serviceId").val() == "") {
            // bootbox.alert("请先设置单表服务信息!");
            showMsg("请先设置单表服务信息!", "warning");
            setTimeout(getgo, 200);
            return;
        }
        showCacheFieldTable();
    });

    $("#btn_cacheImport").click(function () {
        $("#uploadDataExcel").modal('show');
    });

    $("#btn_cacheDownload").click(function () {
        var posurl = postPath + '/system/queryfield/getQueryFieldList';
        var condition = {serviceId: $("#hid_serviceId").val(), serviceType: 1, grade: '', paramType: 1};
        $.post(posurl, condition, function (data) {
            if (data != null && data.length > 0) {
                window.location.href = postPath + "/system/queryfieldcache/exportFieldCacheInfoExcel?serviceId=" + $("#hid_serviceId").val();
            } else {
                // bootbox.alert("请先添加服务查询列配置！");
                showMsg("请先添加服务查询列配置!", "warning");
            }
        }, 'json');

    });

    $('#fieldCachemation').fileinput({
        language: 'zh', //设置语言
        uploadUrl: postPath + '/system/queryfieldcache/uploadFieldCacheInformation', //上传的地址
        maxFileCount: 1,
        browseClass: "btn blue-steel", //按钮样式
        uploadAsync: false, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove: true, //显示移除按钮
        showPreview: false, //是否显示预览
        allowedFileExtensions: ['xls', 'xlsx'],
        uploadExtraData: {
            serviceId: $("#hid_serviceId").val(),
            serviceType: $("#hid_servertype").val(),
            pcode: $("#hid_projectid").val()
        },
    }).on("filebatchuploadsuccess", function (event, data, previewId, index) {    //一个文件上传成功
        //console.log('文件上传成功！'+data.jqXHR.responseJSON.msg);
        if (data.response.result) {
            // bootbox.alert('文件上传成功！');
            showMsg("文件上传成功!", "success");
            showCacheFieldTable();
            $("#uploadDataExcel").modal('hide');
        } else {
            // bootbox.alert(data.response.message);
            showMsg("文件上传失败!", "error");
        }
    });

    //开启模态框添加
    $("#btn_cacheAdd").click(function () {
        editcacheparmetercode = 1;
        //console.info();+ "(" + res[i].fieldnameCn + ")"
        $.ajax({
            type: 'POST',
            url: postPath + '/system/queryfield/getQueryFieldList',
            async: false,
            data: {serviceId: $("#hid_serviceId").val(), serviceType: 1, grade: '', paramType: 1},
            success: function (res) {
                var viewstr = "";
                if (res != null) {
                    for (var i = 0; i < res.length; i++) {
                        viewstr += "<div class=\"form-group\">";
                        viewstr += "<label class=\"col-md-3 control-label\">" + res[i].parametercode + "</label>";
                        viewstr += "<div class=\"col-md-9\">";
                        viewstr += "<input type=\"hidden\" name=\"fieldguid\", value=\"" + res[i].guid + "\"/>";
                        viewstr += "<input type=\"hidden\" name=\"parametercode\", value=\"" + res[i].parametercode + "\"/>";

                        viewstr += "<select name='parameterconfig' class='form-control input-inline col-md-5 date-select' onchange='changeInputWay(this)'>";
                        viewstr += " <option value='customDefind'>固定值</option>";
                        var funcswitch = getFunctionConfig();
                        if (funcswitch != null && funcswitch.length > 0) {
                            for (var j = 0; j < funcswitch.length; j++) {
                                viewstr += " <option value='" + funcswitch[j].guid + "'>" + funcswitch[j].functitle + "</option>";
                            }
                        }
                        viewstr += "</select>";
                        viewstr += "<input type='text' class='form-control input-inline input-cache' name='parametervalue' />";

                        viewstr += "</div>";
                        viewstr += "</div>";
                    }
                }
                $("#Edit_Parmeter_Value").html(viewstr);
            }
        });
        $("#EditQueryCacheContent").modal('show');
    });
    //保存条件缓存配置
    $("#btn_savecachefield").click(function () {
        var parametergroup = null;
        var saveurl = "";
        if (editcacheparmetercode == 1) {//添加
            var parametergroup = Math.random().toString(36).substr(2);
            saveurl = postPath + '/system/queryfieldcache/addQueryFieldCacheList';
        } else if (editcacheparmetercode == 2) {//修改
            saveurl = postPath + '/system/queryfieldcache/updateQueryFieldCacheList';
        }
        var formGroups = $("#Edit_Parmeter_Value").children(".form-group");
        if (formGroups == null || formGroups.length <= 0)
            return;
        var groupsArray = new Array();

        for (var i = 0; i < formGroups.length; i++) {
            var guid = $(formGroups[i]).find("input[name='guid']").val();
            var fieldguid = $(formGroups[i]).find("input[name='fieldguid']").val();
            var parametervalue = $(formGroups[i]).find("input[name='parametervalue']").val();
            var parameterconfig = $(formGroups[i]).find("select[name='parameterconfig']").find("option:selected").val();
            var parametercode = $(formGroups[i]).find("input[name='parametercode']").val();
            var valide = valiParmeters(parametercode, parametervalue, parameterconfig);
            if (!valide) return;
            var cachefield = {
                guid: guid,
                fieldaddonsguid: fieldguid,
                parametervalue: parametervalue,
                parameterconfig: parameterconfig,
                parametergroup: parametergroup
            };
            groupsArray.push(cachefield);
        }
        ;
        $.ajax({
            type: 'POST',
            url: saveurl,
            async: false,
            data: JSON.stringify(groupsArray),
            dataType: 'json',
            contentType: "application/json",
            success: function (res) {
                if (res.success) {
                    //bootbox.alert("添加条件缓存配置成功!");
                    showMsg("添加条件缓存配置成功!", "success");
                    $("#EditQueryCacheContent").modal('hide');
                    showCacheFieldTable();
                }
            },
            error: function (res) {
                showMsg("添加条件缓存配置异常!", "error");
                //bootbox.alert("添加条件缓存配置异常!");
            }
        });

    });


    /*****************End 服务缓存配置************************/
    // var date = threedaysago("3","yyyy-MM-dd");
    // alert(date)
    //valiParmeters("123","22");
});

/****************************缓存配置****************************************/
//删除缓存配置
function deletecachefieldgroup(group) {
    $.ajax({
        type: 'POST',
        url: postPath + '/system/queryfieldcache/deleteQueryFieldCacheList',
        async: false,
        data: {
            serviceId: $("#hid_serviceId").val(),
            serviceType: $("#hid_servertype").val(),
            parametergroup: group
        },
        success: function (res) {
            if (res.success) {
                // bootbox.alert("删除条件缓存配置成功!");
                showMsg("删除条件缓存配置成功!", "success");
                showCacheFieldTable();
                //$("#EditQueryCacheContent").modal('hide');
            }
        },
        error: function (res) {
            // bootbox.alert("删除条件缓存配置异常!");
            showMsg("删除条件缓存配置异常!", "error");
            showCacheFieldTable();
        }
    });
}

//开启模态框修改
function editcachefieldgroup(group) {
    editcacheparmetercode = 2;
    $.ajax({
        type: 'POST',
        url: postPath + '/system/queryfieldcache/queryCacheFieldByServiceIdGroupId',
        async: false,
        data: {serviceId: $("#hid_serviceId").val(), serviceType: $("#hid_servertype").val(), parametergroup: group},
        success: function (res) {
            var viewstr = "";
            if (res != null) {
                for (var i = 0; i < res.length; i++) {
                    viewstr += "<div class=\"form-group\">";
                    viewstr += "<label class=\"col-md-3 control-label\">" + res[i].parametercode + "</label>";
                    viewstr += "<div class=\"col-md-9\">";
                    viewstr += "<input type=\"hidden\" name=\"guid\", value=\"" + res[i].guid + "\"/>";
                    viewstr += "<input type=\"hidden\" name=\"fieldguid\", value=\"" + res[i].fieldaddonsguid + "\"/>";
                    viewstr += "<input type=\"hidden\" name=\"parametercode\", value=\"" + res[i].parametercode + "\"/>";

                    viewstr += "<select name='parameterconfig' class='form-control input-inline col-md-5 date-select' data-value='" + res[i].parameterconfig + "' onchange='changeInputWay(this)'>";
                    viewstr += " <option value='customDefind'>固定值</option>";
                    var funcswitch = getFunctionConfig();
                    if (funcswitch != null && funcswitch.length > 0) {
                        for (var j = 0; j < funcswitch.length; j++) {
                            if (res[i].parameterconfig == funcswitch[j].guid) {
                                viewstr += " <option value='" + funcswitch[j].guid + "' selected='selected'>" + funcswitch[j].functitle + "</option>";
                            } else {
                                viewstr += " <option value='" + funcswitch[j].guid + "'>" + funcswitch[j].functitle + "</option>";
                            }
                        }
                    }
                    viewstr += "</select>";
                    viewstr += "<input type='text' class='form-control input-inline input-cache' value='" + res[i].parametervalue + "' name='parametervalue' />";

                    viewstr += "<input type=\"hidden\" name=\"parametergroup\", value=\"" + res[i].parametergroup + "\"/>";
                    viewstr += "</div>";
                    viewstr += "</div>";
                    // if (i < res.length-1)
                    //     viewstr += "<hr/>";
                }
            }
            $("#Edit_Parmeter_Value").html(viewstr);

        }
    });
    $("#EditQueryCacheContent").modal('show');
}

//列表缓存展示
function showCacheFieldTable() {
    var columns = new Array();
    var posurl = postPath + '/system/queryfield/getQueryFieldList';
    var condition = {serviceId: $("#hid_serviceId").val(), serviceType: 1, grade: '', paramType: 1};
    $.post(posurl, condition, function (data) {
        if (data != null) {
            for (var i = 0; i < data.length; i++) {
                var column = {
                    title: data[i].parametercode,
                    field: data[i].parametercode,
                    align: 'center',
                    valign: 'middle'
                };
                columns.push(column);
            }
            var groupcolumn = {
                title: '参数组',
                field: 'parametergroup',
                align: 'left',
                valign: 'middle',
                visible: false,
            };
            columns.push(groupcolumn);
            var editcolumn = {
                title: '操作',
                field: 'parametergroup',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    var btn = "<button class='btn blue-steel' onclick='editcachefieldgroup(\"" + row.parametergroup + "\");'><i class='fa fa-save'></i>编辑</button>"
                        + "<button class='btn blue-steel' onclick='deletecachefieldgroup(\"" + row.parametergroup + "\");'><i class='fa fa-edit'></i>删除</button>";
                    return btn;
                }
            }
            columns.push(editcolumn);
            $("#tb_showfieldCacheList").bootstrapTable('destroy').bootstrapTable({
                url: postPath + '/system/queryfieldcache/getQueryFieldCacheConfigByServiceId',
                undefinedText: '-',
                striped: true, // 是否显示行间隔色
                queryParams: {
                    serviceId: $("#hid_serviceId").val(),
                    serviceType: $("#hid_servertype").val()
                    //parametergroup : group[i].parametergroup
                },
                uniqueId: "guid", // 每一行的唯一标识
                columns: columns,
            });
        }
    }, "json");

}

//获取函数脚本
function getFunctionConfig() {
    var func = null;
    $.ajax({
        type: 'POST',
        url: postPath + '/system/sysfunc/getSysFunctionByPcode',
        async: false,
        data: {pcode: $("#hid_projectid").val()},
        success: function (res) {
            if (res != null) {
                func = res;
            }
        }
    });
    return func;
}

function queryCacheFieldGroup() {
    var group_obj;
    $.ajax({
        type: 'POST',
        url: postPath + '/system/queryfieldcache/queryCacheFieldGroup',
        async: false,
        data: {serviceId: $("#hid_serviceId").val(), serviceType: $("#hid_servertype").val()},
        success: function (res) {
            if (res != null) {
                group_obj = res;
            }
        }
    });
    return group_obj
}

// 更改定义选项
function changeInputWay(obj) {
    var $dateSelect = $(obj);
    var $input = $dateSelect.next();
    var selectVal = $dateSelect.find("option:selected").val();
    var fmt = $dateSelect.data('format');

    if (selectVal === "customDefind") {
        $input.val("");
    } else {
        $input.datetimepicker('remove');
        var funcswitch = getFunctionConfig();
        for (var j = 0; j < funcswitch.length; j++) {
            if (selectVal == funcswitch[j].guid) {
                $input.val(funcswitch[j].methodname);
            }
        }
    }
}

function valiParmeters(param, value, config) {
    if (config === "customDefind") return true;
    var reg = /^\w+\([\s\S]*\)/
    value = value.replace(/\s+/g, "");
    if (!reg.test(value)) {
        $("#valide_parmeters").html("请输入正确的" + param + "函数格式");
        return false;
    }
    var funcs = getFunctionConfig();
    for (var j = 0; j < funcs.length; j++) {
        if (config === funcs[j].guid) {
            // if(value === funcs[j].methodname.replace(/\s+/g,"")) {
            //    $("#valide_parmeters").html("请输入正确的"+ param +"函数！");
            // }
            var fstart = funcs[j].methodname.indexOf("(") + 1;
            var fstop = funcs[j].methodname.indexOf(")");
            var funcsize = funcs[j].methodname.substring(fstart, fstop).split(",");
            var vstart = value.indexOf("(") + 1;
            var vstop = value.indexOf(")");
            var valuesize = value.substring(vstart, vstop).split(",");
            if (funcsize.length != valuesize.length) {
                $("#valide_parmeters").html("请输入正确的" + param + "函数参数");
                return false;
            }
        }
    }
    return true;
}

/****************************缓存配置****************************************/
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function GetQueryStringSeachTxt(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}

//子页面调用父页面方法-关闭模态框
function closeModul() {
    $("#FieldModul").modal('hide');
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
